import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import NotFound from '../views/NotFound.vue'
import store from '@/store'

Vue.use(VueRouter)

const PageRoule = {
  path: '/menu/page',
  component: () => import('@/views/Page.vue')
}

const PowerRoule = {
  path: '/menu/power',
  component: () => import('@/views/Power.vue')
}

//  实现路由与二级权限映射关系
const ruleMapping = {
  '/menu/page': PageRoule,
  '/menu/power': PowerRoule
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: () => import('@/views/welcome')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') next()
  const token = sessionStorage.getItem('token')
  if (!token) {
    next('/login')
  } else {
    next()
  }
})

export function initDynamicRoutes () {
  //  根据二级权限，对路由规则进行动态添加
  const currentRoutes = router.options.routes
  if (store.state.rightList !== '[]') {
    store.state.rightList.forEach(element => {
      element.children.forEach((item) => {
        const temp = ruleMapping[item.path]
        temp.meta = item.rights
        currentRoutes[0].children.push(temp)
      })
    })
  }
  router.addRoutes(currentRoutes)
}

export default router
